import BlockIcon from '@/components/workflow/block-icon'
import { WorkflowType } from '@/components/workflow/types'
import { useWorkFlowStore } from '@/store/workflowStore'
import cn from '@/util/classnames'
import { Card } from 'antd'
import { Menu } from 'lucide-react'
import { generateNextNodeName, workflowTemplateList } from '../constants'
import './index.less'

const gridStyle: React.CSSProperties = {
  width: '100%',
  margin: '16px'
}

export default function ExtraSidebar({ flow }: { flow: WorkflowType }) {
  const { flowInstance } = useWorkFlowStore()

  function onDragStart(event: React.DragEvent<any>, data) {
    createNodeFromTemplate(event, data, `${data.title}_`)
  }
  /* 初始化生成nodedata */
  function createNodeFromTemplate(event, template, name = '') {
    const newData = { ...template }
    if (flowInstance && Object.keys(flowInstance).length > 0) {
      newData.title = generateNextNodeName(flowInstance.getNodes(), name)
    }
    const crt = event.currentTarget.cloneNode(true)
    crt.style.position = 'absolute'
    crt.style.top = '-500px'
    crt.style.right = '-500px'
    crt.classList.add('cursor-grabbing')
    document.body.appendChild(crt)
    event.dataTransfer.setDragImage(crt, 0, 0)
    event.dataTransfer.setData('nodedata', JSON.stringify(newData))
  }

  return (
    <div className="workflow-sidebar-container flex h-full w-52 flex-col overflow-hidden bg-[#fcfcfd] scrollbar-hide">
      <div className="mx-[24px] h-[48px] text-[16px] font-[600] leading-[48px]">选择节点：</div>
      <Card className="flex h-full w-52 flex-col overflow-auto border-none bg-[#fcfcfd]">
        {workflowTemplateList.map((template, index) => (
          <div
            key={template.type}
            draggable
            className={cn('mx-[16px] my-[8px]', index === 0 && 'mt-0')}
            onDragStart={event => {
              onDragStart(event, template)
            }}
            onDragEnd={e => {
              document.body.removeChild(document.getElementsByClassName('cursor-grabbing')[0])
            }}
          >
            <Card.Grid style={gridStyle} className="template-card-item flex flex-row border-none">
              <BlockIcon className="mr-1 shrink-0" type={template.node_type} size="md" />
              <div className="flex w-[100%] flex-row items-center justify-between">
                <div>{template.title}</div>
                <Menu className="side-bar-components-icon " />
              </div>
            </Card.Grid>
          </div>
        ))}
      </Card>
    </div>
  )
}
